<template>
  <div class="checkout-container">
    <div class="checkout-header">
      <el-page-header @back="goBack" title="确认订单" />
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="8" animated />
    </div>
    
    <template v-else>
      <!-- 收货地址选择 -->
      <el-card class="address-card">
        <template #header>
          <div class="card-header">
            <span>收货地址</span>
            <el-button type="text" @click="showAddressDialog = true">选择地址</el-button>
          </div>
        </template>
        
        <div v-if="selectedAddress" class="selected-address">
          <div class="address-info">
            <div class="contact-info">
              <span class="contact-name">{{ selectedAddress.contactName }}</span>
              <span class="contact-phone">{{ selectedAddress.phone }}</span>
              <el-tag v-if="selectedAddress.isDefault" type="primary" size="small">默认</el-tag>
            </div>
            <div class="address-detail">
              {{ formatAddress(selectedAddress) }}
            </div>
          </div>
        </div>
        
        <div v-else class="no-address">
          <el-empty description="请选择收货地址">
            <el-button type="primary" @click="showAddressDialog = true">选择地址</el-button>
          </el-empty>
        </div>
      </el-card>
      
      <!-- 商品信息 -->
      <el-card class="products-card">
        <template #header>
          <div class="card-header">
            <span>商品信息 ({{ selectedItems.length }}件)</span>
          </div>
        </template>
        
        <div class="product-list">
          <div class="product-item" v-for="item in selectedItems" :key="item.productId">
            <div class="product-image">
              <img :src="item.mainImageUrl || '/assets/product-default.jpg'" :alt="item.name">
            </div>
            <div class="product-info">
              <div class="product-name">{{ item.name }}</div>
              <div class="product-spec">数量: {{ item.quantity }}</div>
            </div>
            <div class="product-price">
              <div class="unit-price">¥{{ item.price.toFixed(2) }}</div>
              <div class="subtotal">小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 优惠信息 -->
      <el-card class="discount-card" v-if="hasDiscounts">
        <template #header>
          <div class="card-header">
            <span>优惠信息</span>
          </div>
        </template>
        
        <div class="discount-list">
          <div class="discount-item" v-if="discountAmount > 0">
            <span>商品优惠</span>
            <span class="discount-value">-¥{{ discountAmount.toFixed(2) }}</span>
          </div>
          <div class="discount-item" v-if="shippingDiscount > 0">
            <span>运费优惠</span>
            <span class="discount-value">-¥{{ shippingDiscount.toFixed(2) }}</span>
          </div>
        </div>
      </el-card>
      
      <!-- 费用明细 -->
      <el-card class="price-card">
        <div class="price-detail">
          <div class="price-item">
            <span>商品总额</span>
            <span>¥{{ originalTotal.toFixed(2) }}</span>
          </div>
          <div class="price-item" v-if="discountAmount > 0">
            <span>商品优惠</span>
            <span class="discount-text">-¥{{ discountAmount.toFixed(2) }}</span>
          </div>
          <div class="price-item">
            <span>运费</span>
            <span>{{ shippingFee === 0 ? '免运费' : `¥${shippingFee.toFixed(2)}` }}</span>
          </div>
          <div class="price-item total-item">
            <span>实付金额</span>
            <span class="total-price">¥{{ finalTotal.toFixed(2) }}</span>
          </div>
        </div>
      </el-card>
      
      <!-- 订单备注 -->
      <el-card class="remark-card">
        <template #header>
          <span>订单备注</span>
        </template>
        <el-input
          v-model="orderRemark"
          type="textarea"
          :rows="3"
          placeholder="如有特殊要求请在此填写（选填）"
          maxlength="200"
          show-word-limit
        />
      </el-card>
      
      <!-- 提交订单 -->
      <div class="submit-section">
        <div class="price-summary">
          <div class="total-info">
            <span>实付金额：</span>
            <span class="final-price">¥{{ finalTotal.toFixed(2) }}</span>
          </div>
        </div>
        <el-button
          type="primary"
          size="large"
          :disabled="!selectedAddress || submitting"
          :loading="submitting"
          @click="submitOrder"
        >
          提交订单
        </el-button>
      </div>
    </template>
    
    <!-- 地址选择弹窗 -->
    <el-dialog v-model="showAddressDialog" title="选择收货地址" width="80%" :close-on-click-modal="false">
      <div v-if="loadingAddresses" class="loading-addresses">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else-if="addresses.length === 0" class="no-addresses">
        <el-empty description="暂无收货地址，请先添加地址" />
      </div>
      <div v-else class="address-list">
        <div
          v-for="address in addresses"
          :key="address.id"
          class="address-option"
          :class="{ selected: selectedAddress?.id === address.id }"
          @click="selectAddress(address)"
        >
          <div class="address-content">
            <div class="contact-info">
              <span class="contact-name">{{ address.contactName }}</span>
              <span class="contact-phone">{{ address.phone }}</span>
              <el-tag v-if="address.isDefault" type="primary" size="small">默认</el-tag>
            </div>
            <div class="address-detail">
              {{ formatAddress(address) }}
            </div>
          </div>
          <div class="address-actions">
            <el-radio
              :model-value="selectedAddress?.id"
              :label="address.id"
              @change="selectAddress(address)"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface Address {
  id: number;
  contactName: string;
  phone: string;
  province: string;
  city: string;
  district: string;
  street: string;
  isDefault: boolean;
}

interface CartItem {
  cartItemId: number;
  productId: number;
  name: string;
  mainImageUrl: string;
  price: number;
  quantity: number;
  stock: number;
}

const route = useRoute()
const router = useRouter()

// 状态管理
const loading = ref(true)
const submitting = ref(false)
const showAddressDialog = ref(false)
const loadingAddresses = ref(false)

// 数据
const selectedItems = ref<CartItem[]>([])
const addresses = ref<Address[]>([])
const selectedAddress = ref<Address | null>(null)
const orderRemark = ref('')

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化地址
const formatAddress = (address: Address) => {
  return `${address.province} ${address.city} ${address.district} ${address.street}`
}

// 计算属性
const originalTotal = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

const discountAmount = computed(() => {
  // 这里可以根据业务逻辑计算折扣，比如满减、优惠券等
  // 暂时返回0，表示没有折扣
  return 0
})

const shippingFee = computed(() => {
  // 满199免运费，否则运费10元
  const subtotal = originalTotal.value - discountAmount.value
  return subtotal >= 199 ? 0 : 10
})

const shippingDiscount = computed(() => {
  // 运费优惠
  return 0
})

const finalTotal = computed(() => {
  return originalTotal.value - discountAmount.value + shippingFee.value - shippingDiscount.value
})

const hasDiscounts = computed(() => {
  return discountAmount.value > 0 || shippingDiscount.value > 0
})

// 选择地址
const selectAddress = (address: Address) => {
  selectedAddress.value = address
}

// 确认地址选择
const confirmAddress = () => {
  showAddressDialog.value = false
}

// 获取购物车选中商品
const fetchSelectedCartItems = async () => {
  try {
    const itemIds = route.query.items as string
    if (!itemIds) {
      ElMessage.warning('没有选择商品')
      router.push('/cart')
      return
    }

    // 获取完整的购物车数据
    const response = await axios.get('/api/user/cart')
    const allCartItems = response.data.items || []
    
    const selectedItemIds = itemIds.split(',').map(id => parseInt(id))
    
    // 过滤出选中的商品，保存购物车项的完整信息
    selectedItems.value = allCartItems.filter((item: any) => 
      selectedItemIds.includes(item.productId)
    ).map((item: any) => ({
      cartItemId: item.id, // 使用后端返回的购物车项ID
      productId: item.productId,
      name: item.name,
      mainImageUrl: item.mainImageUrl,
      price: parseFloat(item.price),
      quantity: item.quantity,
      stock: item.stock
    }))

    if (selectedItems.value.length === 0) {
      ElMessage.warning('选中的商品不存在')
      router.push('/cart')
    }
  } catch (error) {
    console.error('获取购物车商品失败:', error)
    ElMessage.error('获取商品信息失败，请稍后重试')
    router.push('/cart')
  }
}

// 获取收货地址列表
const fetchAddresses = async () => {
  try {
    loadingAddresses.value = true
    const response = await axios.get('/api/user/addresses')
    addresses.value = response.data || []
    
    // 自动选择默认地址
    const defaultAddress = addresses.value.find(addr => addr.isDefault)
    if (defaultAddress) {
      selectedAddress.value = defaultAddress
    } else if (addresses.value.length > 0) {
      selectedAddress.value = addresses.value[0]
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    // 如果获取地址失败，使用空数组
    addresses.value = []
  } finally {
    loadingAddresses.value = false
  }
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (selectedItems.value.length === 0) {
    ElMessage.warning('没有选择商品')
    return
  }

  try {
    submitting.value = true
    
    // 根据后端OrderCreateDto格式准备数据
    const orderData = {
      addressId: selectedAddress.value.id,
      cartItemIds: selectedItems.value.map(item => item.cartItemId),
      remark: orderRemark.value || null
    }

    const response = await axios.post('/api/user/orders', orderData)
    const orderNo = response.data

    ElMessage.success('订单创建成功')
    
    // 跳转到支付页面
    router.push(`/payment/${orderNo}`)
    
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchSelectedCartItems(),
      fetchAddresses()
    ])
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.checkout-header {
  margin-bottom: 20px;
}

.loading-container {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}

.address-card, .products-card, .discount-card, .price-card, .remark-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.selected-address {
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.contact-name {
  font-weight: bold;
}

.contact-phone {
  color: #666;
}

.address-detail {
  color: #333;
  line-height: 1.5;
}

.no-address {
  text-align: center;
  padding: 40px 20px;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: white;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
  border: 1px solid #eee;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-spec {
  font-size: 14px;
  color: #666;
}

.product-price {
  text-align: right;
}

.unit-price {
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 5px;
}

.subtotal {
  font-size: 14px;
  color: #999;
}

.discount-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.discount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #fff7e6;
  border-radius: 4px;
}

.discount-value {
  color: #f56c6c;
  font-weight: bold;
}

.price-detail {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.discount-text {
  color: #f56c6c;
}

.total-item {
  padding-top: 12px;
  border-top: 1px solid #e0e0e0;
  font-size: 16px;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
}

.submit-section {
  position: sticky;
  bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.price-summary {
  flex: 1;
}

.total-info {
  font-size: 16px;
}

.final-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
  margin-left: 10px;
}

.loading-addresses {
  padding: 20px;
}

.no-addresses {
  text-align: center;
  padding: 40px 20px;
}

.address-list {
  max-height: 400px;
  overflow-y: auto;
}

.address-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-option:hover {
  border-color: #409eff;
}

.address-option.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.address-content {
  flex: 1;
}

@media (max-width: 768px) {
  .checkout-container {
    padding: 10px;
  }
  
  .product-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .product-image {
    width: 100%;
    height: 200px;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .product-price {
    margin-top: 10px;
    align-self: flex-end;
    text-align: left;
  }
  
  .submit-section {
    flex-direction: column;
    gap: 15px;
  }
}
</style> 